﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Imageo.bintje;
using System.Web.Security;
using System.Threading;
using log4net;
using System.Drawing;

namespace Imageo
{
    public partial class MasterPage : System.Web.UI.MasterPage
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        int proUserId = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            string strProUserId = Request.QueryString["prouserid"];
            HttpCookie myCookie = new HttpCookie("ImageoSession");

            if (Session["BintjeSession"] == null)
            {
                // If the session has been deleted, we can try to get it back from the cookie
                myCookie = Request.Cookies["ImageoSession"];

                try
                {
                    imageoSession tmpSession = JSONHelper.Deserialize<imageoSession>(myCookie.Value);
                    Session["BintjeSession"] = tmpSession;
                }
                catch
                {
                    Session["BintjeSession"] = null;
                }
            }

            trProHome.Visible = false;

            if (!string.IsNullOrEmpty(strProUserId))
            {
                if (!int.TryParse(strProUserId, out proUserId))
                {
                    Response.Redirect("~/UI/ProErrorGeneric.aspx");
                }
                
                // We have a professional user here
//                imgLogo.ImageUrl = Page.ResolveUrl("~/upload/" + proUserId.ToString() + ".jpg");
                imgLogo.ImageUrl = Page.ResolveUrl("http://bintje-01.hku.nl:7080/imageo/getlogo?userid=" + proUserId.ToString());

                string backColor=Session["proBackground"] as string;
                string foreColor=Session["proForeground"] as string;
                if (!string.IsNullOrEmpty(backColor))
                {
                    masterHeader.Style.Add("background-color", "#" + backColor);
                    masterFooter.Style.Add("background-color", "#" + backColor);
                }

                if (!string.IsNullOrEmpty(foreColor))
                {
                    lblFindTrails.ForeColor = Color.FromName("#" + foreColor);
                }

                masterHeader.Visible=false;
                masterFooter.Visible=false;
                string strBorders=Session["proBorders"] as string;
                if (!string.IsNullOrEmpty(strBorders))
                {
                    if (strBorders=="true")
                    {
                        masterHeader.Visible=true;
                        masterFooter.Visible=true;
                    }
                }

                lnkLogo.HRef = Session["proImageUrl"] as string;

                trProHome.Visible = true;
                lnkProHome.NavigateUrl = "~/pro/" + proUserId.ToString();

                tdLogin.Visible = false;
                divMenuBar.Visible = false;
                divImageoFooter.Visible = false;
            }
            else
            {
            }

            UpdateControls();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Page.Header.DataBind();
        }

        protected void UpdateControls()
        {
            bintje.imageoSession currentSession = Session["BintjeSession"] as imageoSession;
            ltrLoginMessage.Visible = false;
            
            if (currentSession != null)
            {
                lblLoginStatus.Text = string.Format("Welcome {0},", currentSession.login);
                // There is a session
                divLoginMessage.Visible = false;
                divLoginStatus.Visible = true;
                divLogout.Visible = true;
                pnllogin.Visible = false;
                divSignUp.Visible = false;
                divLostPassword.Visible = false;
                divChangePassword.Visible = true;

                divHyperlink3.Visible = true;
                divHyperlink4.Visible = true;
                HyperLink3.NavigateUrl = "~/ui/TrailSearch2.aspx?UserId=" + currentSession.userId.ToString();
            }
            else
            {
                // We don't have a session
                divLoginStatus.Visible = false;
                divLogout.Visible = false;
                pnllogin.Visible = true;
                divSignUp.Visible = true;
                divLostPassword.Visible = true;
                divChangePassword.Visible = false;

                divHyperlink3.Visible = false;
                divHyperlink4.Visible = false;
            }
        }

        protected void lnkLogout_Click(object sender, EventArgs e)
        {
            bintje.imageoSession currentSession = Session["BintjeSession"] as imageoSession;
            if (currentSession == null) return;

            try
            {
                ServiceAPI service = new ServiceAPI();
                if (log.IsErrorEnabled) log.Debug("Calling: service.doLogout(currentSession)");
                logoutResponse response = ServiceHelper.HandleBintjeErrors(null, service.doLogout(currentSession));

                Session["BintjeSession"] = null;
                HttpCookie myCookie = new HttpCookie("ImageoSession");
                myCookie.Value = "";
                myCookie.Expires = DateTime.Now.AddDays(-1);

                // Add the cookie.
                Response.Cookies.Add(myCookie);
            }
            catch (Exception exc)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error(exc.Source + " - " + exc.Message);
                }

                ltrLoginMessage.Visible = true;
                pnllogin.Visible = true;
                lnkSignup.Visible = true;
            }

            UpdateControls();

            String scriptText = "<script language='javascript'> window.location.href='" + Page.ResolveClientUrl("~/ui/home.aspx") + "' </script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Redirect Home", scriptText);
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            // TODO: Maybe later I could make a proper membership provider
            try
            {
                ServiceAPI service = new ServiceAPI();

                string userName = txtUsername.Text.Trim();
                string password = txtPassword.Text.Trim();

                bool IsLocal = HttpContext.Current.Request.Url.AbsoluteUri.StartsWith("http://localhost:");

                if (IsLocal)
                {
                    //                userName = "jleni@matyca.com";
                    //                password = "oagrungkgx";
                    userName = "imageo@kmt.hku.nl";
                    password = "imageo";
                    log.Debug("Auto Login...");
                }

                if (log.IsErrorEnabled) log.Debug("Calling: service.doLogin(userName, password)");
                loginResponse response = ServiceHelper.HandleBintjeErrors(null, service.doLogin(userName, password));

                Session["BintjeSession"] = response.session;
                HttpCookie myCookie = new HttpCookie("ImageoSession");
                myCookie.Value = JSONHelper.Serialize<imageoSession>(response.session);
                myCookie.Expires = DateTime.Now.AddMinutes(30);

                UpdateControls();

                // Add the cookie.
                Response.Cookies.Add(myCookie);
                Response.Redirect(Request.UrlReferrer.ToString());
            }
            catch (ThreadAbortException) { }
            catch (Exception exc)
            {
                ltrLoginMessage.Visible = true;
                pnllogin.Visible = true;
                lnkSignup.Visible = true;
                Session["BintjeSession"] = null;

                if (log.IsErrorEnabled)
                {
                    log.Error(exc.Source + " - " + exc.Message);
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string searchUrl = ResolveUrl("~/UI/TrailSearch2.aspx?searchStr=") + txtSearch.Text;

            if (proUserId > 0)
            {
                Response.Redirect(searchUrl+"&prouserid="+proUserId.ToString());
            }
            else
            {
                Response.Redirect(searchUrl);
            }
        }

    }
}
